import { Box, Button, Container, Grid, Paper, Snackbar, TextField, styled } from "@mui/material";
import { useEffect, useState } from "react";
import fetchData from "../utils/ApiFetch";
import useLocalStorage from "../utils/useLocalStorage";
import { useNavigate } from "react-router-dom";
const apiUrl = process.env.REACT_APP_API_URL;
const captchaHeight = '40px'

const Captcha = styled('div')({
    backgroundColor:'#e3d1d1',
    height:captchaHeight,
    position:'relative',
    maxWidth:'300px',
    userSelect:'none'
});



const Hint = styled('div')({
    position:'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    userSelect:"none"
});

const Block = styled('div')({
    zIndex:99,
    backgroundColor:'#1565c0',
    cursor:'pointer',
    height:captchaHeight,
    width: captchaHeight,
    position:'absolute',
    top:'0px',
});


function SignIn(props) {
    const [token, setToken] = useLocalStorage('token', '')
    const [userName, setUserName] = useState('')
    const [loginSessionId, setLoginSessionId] = useState('')
    const [hasError, setHasError] = useState(false)
    const [message, setMessage] = useState('1111')
    const [startCap, setStartCap] = useState(false)
    const [left, setLeft] = useState(0)
    const [userPassword, setUserPassword] = useState('')
    const [capImg,setCapImg] = useState('')
    const [puzzleImg,setPuzzleImg] = useState('')
    const [puzzleY,setPuzzleY] = useState(0)
    const navigate = useNavigate()
    function handleSubmit(e) {
        const login = async () => {
            let resp = await fetchData(apiUrl+'/login/', 'POST', {userName: userName, userPassword: userPassword,loginSessionId: loginSessionId, captcha: Math.round(left), })
            if (resp.code === 200) {
                setToken(resp.data)
            } else if (resp.code === 400) {
                setHasError(true)
                setMessage(resp.message)
            }
        }
        login()
    }

    useEffect(()=> {
        if (token !== undefined && token !== null && token !== '') {
            navigate('/app/file')
        }
    }, [token])


    useEffect(()=> {
        const fetchCap = async () => {
            let resp = await fetchData(apiUrl+'/getCaptcha')
            if (resp.code === 200) {
                setCapImg(resp.data.img)
                setPuzzleImg(resp.data.puzzle)
                setPuzzleY(resp.data.puzzleY)
                setLoginSessionId(resp.data.id)
            }
        }
        fetchCap()
    }, [])

    useEffect(()=> {
        if (hasError) {
            setTimeout(()=>{setHasError(false)}, 3000)
        }
    }, [hasError])

    function handleBlockMouseDown(e) {
        setStartCap(true)
    }

    function handleBlockMouseUp(e) {
        console.log('handleBlockMouseUp')
        setStartCap(false)
    }

    function handleBlockMouseMove(e) {
        if (startCap) {
            let maxWidth = e.target.parentElement.clientWidth;
            let nx = 0
            if (left+e.movementX < 0) {
                nx = 0
            } else if (left+e.movementX + 40 > maxWidth) {
                nx = maxWidth - 40
            } else {
                nx = left+e.movementX
            }
            setLeft(nx) 
        }
        
    }
    let first = true;
    let lastX = 0;
    function handleTouchMove(e) {

        let maxWidth = e.target.parentElement.clientWidth;
        if (first) {
            lastX = e.changedTouches[0].pageX;
            first = false;
        } else {
           let diff = e.changedTouches[0].pageX - lastX;
           lastX = e.changedTouches[0].pageX
           let nx = 0
            if (left+diff < 0) {
                nx = left
            } else if (left+diff + 40 > maxWidth) {
                nx = maxWidth - 40
            } else {
                nx = left+diff
            }
            setLeft(nx)
        }
        
    }

    function handleTouchEnd(e) {
        first = true;
    }

    return (
        <Container maxWidth='sm' sx={{height:"100vh"}}>
            <Grid container spacing={2} direction={'column'} sx={{justifyContent:'center', height:'100vh'}}>
                <Paper sx={{marginLeft:'16px', paddingTop: '32px', paddingBottom: '32px'}}>
                    <Grid container spacing={2} sx={{justifyContent:'center'}}>
                        <Grid item xs={10}>
                            <Box  sx={{fontSize:'2rem', fontWeight:'900'}}>登录</Box>
                        </Grid>
                        <Grid item xs={10}>
                            <TextField id="userName" label="用户名" variant="filled" value={userName} onChange={(e)=> setUserName(e.target.value)} fullWidth />
                        </Grid>
                        <Grid item xs={10}>
                            <TextField id="userPassword" label="密码" variant="filled" type='password' value={userPassword} onChange={(e)=> setUserPassword(e.target.value)} fullWidth />
                        </Grid>
                        <Grid item xs={10}>
                            <Captcha onMouseMove={handleBlockMouseMove} onMouseLeave={handleBlockMouseUp}>
                                <Block style={{left:left}} onMouseDown={handleBlockMouseDown} onMouseUp={handleBlockMouseUp} onTouchStart={handleBlockMouseDown}  onTouchMove={handleTouchMove} onTouchEnd={handleTouchEnd} /> 
                                <Hint>滑动验证码</Hint>
                                <Box sx={{position: 'relative',top: '-225px',zIndex: '100'}} style={{display: startCap ? 'block' : 'none'}}>
                                    <img style={{position:'absolute', top: puzzleY+'px', left:left+'px'}} src={"data:image/png;base64," + puzzleImg} alt="puzzle"></img>
                                    <img src={"data:image/png;base64," + capImg} alt="cap"></img>
                                </Box>
                            </Captcha>
                        </Grid>
                        <Grid item xs={10} sx={{display:'flex', justifyContent:'space-between'}}>
                            <Button variant='contained' onClick={handleSubmit}>登录</Button>
                            <Button onClick={(e)=>{navigate('/signup')}}>注册</Button>
                        </Grid>
                        
                    </Grid>
                </Paper>
            </Grid> 
            <Snackbar 
                open={hasError}
                message={message}
                anchorOrigin={{vertical:'top', horizontal: 'center'}}
            >
                
            </Snackbar>
        </Container>
    )
}


export default SignIn;